<template>
  <div class="image-convert-tool">
    <div class="tool-header">
      <h1>图片格式转换工具</h1>
      <p>快速转换图片格式，支持多种输出格式</p>
    </div>

    <div class="tool-container">
      <el-row :gutter="20">
        <!-- 上传区域 -->
        <el-col :span="12">
          <div class="upload-section">
            <div class="section-header">
              <h3>上传图片</h3>
            </div>
            
            <div class="upload-area">
              <el-upload
                ref="uploadRef"
                class="upload-dragger"
                drag
                :auto-upload="false"
                :show-file-list="false"
                :on-change="handleFileChange"
                accept="image/*"
              >
                <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                <div class="el-upload__text">
                  将图片拖到此处，或<em>点击上传</em>
                </div>
                <template #tip>
                  <div class="el-upload__tip">
                    支持 JPG、PNG、GIF、WebP、BMP、TIFF 格式
                  </div>
                </template>
              </el-upload>
            </div>
            
            <div class="file-info" v-if="originalFile">
              <h4>原始文件信息</h4>
              <div class="info-grid">
                <div class="info-item">
                  <span class="label">文件名：</span>
                  <span class="value">{{ originalFile.name }}</span>
                </div>
                <div class="info-item">
                  <span class="label">文件大小：</span>
                  <span class="value">{{ formatFileSize(originalFile.size) }}</span>
                </div>
                <div class="info-item">
                  <span class="label">图片尺寸：</span>
                  <span class="value">{{ originalImageSize }}</span>
                </div>
                <div class="info-item">
                  <span class="label">原始格式：</span>
                  <span class="value">{{ getFileFormat(originalFile.type) }}</span>
                </div>
              </div>
            </div>
          </div>
        </el-col>

        <!-- 转换设置和结果 -->
        <el-col :span="12">
          <div class="convert-section">
            <div class="section-header">
              <h3>转换设置</h3>
            </div>
            
            <div class="convert-options" v-if="originalFile">
              <div class="option-group">
                <label>目标格式：</label>
                <el-select v-model="targetFormat" placeholder="选择目标格式" size="large">
                  <el-option
                    v-for="format in supportedFormats"
                    :key="format.value"
                    :label="format.label"
                    :value="format.value"
                    :disabled="format.value === getFileFormat(originalFile.type)"
                  >
                    <span style="float: left">{{ format.label }}</span>
                    <span style="float: right; color: #8492a6; font-size: 13px">{{ format.description }}</span>
                  </el-option>
                </el-select>
              </div>
              
              <div class="option-group" v-if="targetFormat === 'jpeg'">
                <label>JPEG 质量：</label>
                <el-slider
                  v-model="jpegQuality"
                  :min="10"
                  :max="100"
                  :step="5"
                  show-input
                  :show-input-controls="false"
                />
              </div>
              
              <div class="option-group" v-if="targetFormat === 'png'">
                <label>PNG 压缩：</label>
                <el-radio-group v-model="pngCompression">
                  <el-radio label="none">无压缩</el-radio>
                  <el-radio label="fast">快速压缩</el-radio>
                  <el-radio label="best">最佳压缩</el-radio>
                </el-radio-group>
              </div>
              
              <div class="option-group" v-if="targetFormat === 'webp'">
                <label>WebP 质量：</label>
                <el-slider
                  v-model="webpQuality"
                  :min="10"
                  :max="100"
                  :step="5"
                  show-input
                  :show-input-controls="false"
                />
              </div>
              
              <div class="option-group">
                <label>保持透明度：</label>
                <el-switch v-model="keepTransparency" />
                <span class="switch-tip">（仅PNG和WebP支持）</span>
              </div>
            </div>
            
            <div class="convert-actions" v-if="originalFile">
              <el-button 
                type="primary" 
                @click="convertImage"
                :loading="isConverting"
                :disabled="!targetFormat"
                size="large"
              >
                <el-icon><Refresh /></el-icon>
                开始转换
              </el-button>
              <el-button @click="resetAll" size="large">重置</el-button>
            </div>
            
            <!-- 转换结果 -->
            <div class="result-section" v-if="convertedFile">
              <div class="section-header">
                <h3>转换结果</h3>
              </div>
              
              <div class="result-info">
                <div class="comparison">
                  <div class="comparison-item">
                    <h4>转换前</h4>
                    <div class="format-info">
                      <span class="format">{{ getFileFormat(originalFile.type).toUpperCase() }}</span>
                      <span class="size">{{ formatFileSize(originalFile.size) }}</span>
                    </div>
                  </div>
                  <div class="comparison-item">
                    <h4>转换后</h4>
                    <div class="format-info">
                      <span class="format">{{ targetFormat.toUpperCase() }}</span>
                      <span class="size">{{ formatFileSize(convertedFile.size) }}</span>
                    </div>
                  </div>
                </div>
                
                <div class="conversion-stats">
                  <el-tag type="success" size="large">
                    转换成功
                  </el-tag>
                  <el-tag type="info" size="large">
                    新格式: {{ targetFormat.toUpperCase() }}
                  </el-tag>
                </div>
              </div>
              
              <div class="result-actions">
                <el-button @click="downloadConverted" type="primary" size="large">
                  <el-icon><Download /></el-icon>
                  下载转换图片
                </el-button>
                <el-button @click="previewImage" size="large">
                  <el-icon><View /></el-icon>
                  预览图片
                </el-button>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>

      <!-- 格式说明 -->
      <div class="format-info-section">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>格式说明</span>
            </div>
          </template>
          
          <div class="format-grid">
            <div class="format-item" v-for="format in formatDescriptions" :key="format.name">
              <div class="format-header">
                <h4>{{ format.name }}</h4>
                <el-tag :type="format.type" size="small">{{ format.extension }}</el-tag>
              </div>
              <p>{{ format.description }}</p>
              <div class="format-features">
                <span class="feature" v-for="feature in format.features" :key="feature">
                  {{ feature }}
                </span>
              </div>
            </div>
          </div>
        </el-card>
      </div>

      <!-- 使用说明 -->
      <div class="tool-info">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>使用说明</span>
            </div>
          </template>
          
          <div class="info-content">
            <h4>转换流程：</h4>
            <ol>
              <li>上传需要转换的图片文件</li>
              <li>选择目标输出格式</li>
              <li>调整格式相关参数（如质量、压缩等）</li>
              <li>点击"开始转换"按钮</li>
              <li>下载转换后的图片</li>
            </ol>
            
            <h4>格式选择建议：</h4>
            <ul>
              <li><strong>网页显示：</strong>推荐使用 WebP 或 JPEG</li>
              <li><strong>透明背景：</strong>使用 PNG 格式</li>
              <li><strong>高质量打印：</strong>使用 PNG 或 TIFF</li>
              <li><strong>动画图片：</strong>使用 GIF 格式</li>
            </ul>
            
            <h4>注意事项：</h4>
            <div class="warning">
              <p>⚠️ 转换过程中可能会损失一些图片质量</p>
              <p>⚠️ 某些格式不支持透明度，转换时会自动填充背景</p>
              <p>⚠️ 转换后的图片仅在前端处理，不会上传到服务器</p>
            </div>
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { UploadFilled, Refresh, Download, View } from '@element-plus/icons-vue'

const uploadRef = ref()
const originalFile = ref(null)
const convertedFile = ref(null)
const originalImageSize = ref('')
const targetFormat = ref('')
const jpegQuality = ref(90)
const webpQuality = ref(90)
const pngCompression = ref('fast')
const keepTransparency = ref(true)
const isConverting = ref(false)

const supportedFormats = [
  { value: 'jpeg', label: 'JPEG', description: '适合照片' },
  { value: 'png', label: 'PNG', description: '支持透明度' },
  { value: 'webp', label: 'WebP', description: '现代格式' },
  { value: 'gif', label: 'GIF', description: '支持动画' },
  { value: 'bmp', label: 'BMP', description: '位图格式' }
]

const formatDescriptions = [
  {
    name: 'JPEG',
    extension: '.jpg/.jpeg',
    type: 'success',
    description: '最常用的图片格式，压缩效果好，适合照片和复杂图像。',
    features: ['有损压缩', '文件小', '兼容性好', '不支持透明度']
  },
  {
    name: 'PNG',
    extension: '.png',
    type: 'primary',
    description: '支持透明度的无损压缩格式，适合图标和简单图像。',
    features: ['无损压缩', '支持透明度', '文件较大', '适合图标']
  },
  {
    name: 'WebP',
    extension: '.webp',
    type: 'warning',
    description: 'Google开发的现代图片格式，压缩率更高，质量更好。',
    features: ['高压缩率', '支持透明度', '现代浏览器', '质量好']
  },
  {
    name: 'GIF',
    extension: '.gif',
    type: 'info',
    description: '支持动画的图片格式，颜色数量有限，适合简单动画。',
    features: ['支持动画', '颜色有限', '文件小', '兼容性好']
  },
  {
    name: 'BMP',
    extension: '.bmp',
    type: '',
    description: 'Windows位图格式，无压缩，文件较大但质量无损。',
    features: ['无压缩', '文件大', '质量无损', 'Windows标准']
  }
]

const handleFileChange = (file) => {
  const fileObj = file.raw
  if (!fileObj) return
  
  if (!fileObj.type.startsWith('image/')) {
    ElMessage.error('请选择图片文件')
    return
  }
  
  originalFile.value = fileObj
  
  // 获取图片尺寸
  const img = new Image()
  img.onload = () => {
    originalImageSize.value = `${img.width} × ${img.height}`
  }
  img.src = URL.createObjectURL(fileObj)
  
  ElMessage.success('图片上传成功')
}

const convertImage = async () => {
  if (!originalFile.value || !targetFormat.value) {
    ElMessage.warning('请上传图片并选择目标格式')
    return
  }
  
  isConverting.value = true
  
  try {
    // 模拟转换过程
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    const canvas = document.createElement('canvas')
    const ctx = canvas.getContext('2d')
    const img = new Image()
    
    img.onload = () => {
      canvas.width = img.width
      canvas.height = img.height
      
      // 处理透明度
      if (!keepTransparency.value && (targetFormat.value === 'jpeg' || targetFormat.value === 'bmp')) {
        // 填充白色背景
        ctx.fillStyle = '#FFFFFF'
        ctx.fillRect(0, 0, canvas.width, canvas.height)
      }
      
      ctx.drawImage(img, 0, 0)
      
      // 获取转换后的数据
      const mimeType = getMimeType(targetFormat.value)
      const quality = getQuality(targetFormat.value)
      
      canvas.toBlob((blob) => {
        convertedFile.value = blob
        isConverting.value = false
        ElMessage.success('图片转换完成')
      }, mimeType, quality)
    }
    
    img.src = URL.createObjectURL(originalFile.value)
  } catch (error) {
    isConverting.value = false
    ElMessage.error('转换失败：' + error.message)
  }
}

const getMimeType = (format) => {
  const mimeTypes = {
    jpeg: 'image/jpeg',
    png: 'image/png',
    webp: 'image/webp',
    gif: 'image/gif',
    bmp: 'image/bmp'
  }
  return mimeTypes[format] || 'image/jpeg'
}

const getQuality = (format) => {
  if (format === 'jpeg') return jpegQuality.value / 100
  if (format === 'webp') return webpQuality.value / 100
  return 1
}

const getFileFormat = (mimeType) => {
  return mimeType.split('/')[1] || 'unknown'
}

const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 Bytes'
  const k = 1024
  const sizes = ['Bytes', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

const downloadConverted = () => {
  if (!convertedFile.value) {
    ElMessage.warning('没有可下载的文件')
    return
  }
  
  const url = URL.createObjectURL(convertedFile.value)
  const a = document.createElement('a')
  a.href = url
  a.download = `converted_${originalFile.value.name.split('.')[0]}.${targetFormat.value}`
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
  URL.revokeObjectURL(url)
  
  ElMessage.success('文件下载开始')
}

const previewImage = () => {
  if (!convertedFile.value) {
    ElMessage.warning('没有可预览的文件')
    return
  }
  
  const url = URL.createObjectURL(convertedFile.value)
  window.open(url, '_blank')
}

const resetAll = () => {
  originalFile.value = null
  convertedFile.value = null
  originalImageSize.value = ''
  targetFormat.value = ''
  jpegQuality.value = 90
  webpQuality.value = 90
  pngCompression.value = 'fast'
  keepTransparency.value = true
  uploadRef.value?.clearFiles()
  ElMessage.info('已重置所有设置')
}
</script>

<style scoped>
.image-convert-tool {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.tool-header {
  text-align: center;
  margin-bottom: 40px;
}

.tool-header h1 {
  font-size: 2.5rem;
  color: #333;
  margin-bottom: 10px;
}

.tool-header p {
  color: #666;
  font-size: 1.1rem;
}

.tool-container {
  margin-bottom: 40px;
}

.upload-section,
.convert-section {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  border: 1px solid #f0f0f0;
  height: 100%;
}

.section-header {
  margin-bottom: 20px;
}

.section-header h3 {
  color: #333;
  margin: 0;
  font-size: 1.3rem;
}

.upload-area {
  margin-bottom: 20px;
}

.upload-dragger {
  width: 100%;
}

.file-info {
  background: #f8f9fa;
  padding: 20px;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}

.file-info h4 {
  margin: 0 0 15px 0;
  color: #333;
  font-size: 1.1rem;
}

.info-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 10px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  padding: 8px 0;
  border-bottom: 1px solid #e9ecef;
}

.info-item:last-child {
  border-bottom: none;
}

.label {
  font-weight: 500;
  color: #666;
}

.value {
  color: #333;
  font-family: 'Courier New', monospace;
}

.convert-options {
  margin-bottom: 30px;
}

.option-group {
  margin-bottom: 25px;
}

.option-group label {
  display: block;
  margin-bottom: 10px;
  font-weight: 500;
  color: #333;
}

.switch-tip {
  margin-left: 10px;
  color: #666;
  font-size: 0.9rem;
}

.convert-actions {
  display: flex;
  gap: 12px;
  margin-top: 30px;
}

.result-section {
  margin-top: 30px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}

.result-info {
  margin-bottom: 20px;
}

.comparison {
  display: flex;
  justify-content: space-around;
  margin-bottom: 20px;
}

.comparison-item {
  text-align: center;
}

.comparison-item h4 {
  margin: 0 0 15px 0;
  color: #333;
}

.format-info {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.format {
  font-size: 1.2rem;
  font-weight: bold;
  color: #667eea;
}

.size {
  color: #666;
  font-size: 0.9rem;
}

.conversion-stats {
  display: flex;
  justify-content: center;
  gap: 15px;
}

.result-actions {
  display: flex;
  gap: 12px;
  justify-content: center;
}

.format-info-section {
  margin: 40px 0;
}

.card-header {
  font-weight: bold;
  color: #333;
}

.format-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
}

.format-item {
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}

.format-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.format-header h4 {
  margin: 0;
  color: #333;
}

.format-item p {
  color: #666;
  margin-bottom: 15px;
  line-height: 1.5;
}

.format-features {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.feature {
  padding: 4px 8px;
  background: #667eea;
  color: white;
  border-radius: 4px;
  font-size: 0.8rem;
}

.tool-info {
  margin-top: 40px;
}

.info-content h4 {
  color: #333;
  margin: 20px 0 10px 0;
  font-size: 1.1rem;
}

.info-content p {
  color: #666;
  line-height: 1.6;
  margin-bottom: 15px;
}

.info-content ol,
.info-content ul {
  color: #666;
  padding-left: 20px;
  margin-bottom: 15px;
}

.info-content li {
  margin-bottom: 5px;
}

.warning {
  background: #fff3cd;
  padding: 15px;
  border-radius: 8px;
  border-left: 4px solid #ffc107;
  margin: 15px 0;
}

.warning p {
  margin: 5px 0;
  color: #856404;
}

@media (max-width: 768px) {
  .tool-header h1 {
    font-size: 2rem;
  }
  
  .info-grid {
    grid-template-columns: 1fr;
  }
  
  .comparison {
    flex-direction: column;
    gap: 15px;
  }
  
  .conversion-stats {
    flex-direction: column;
    align-items: center;
  }
  
  .result-actions {
    flex-direction: column;
  }
  
  .format-grid {
    grid-template-columns: 1fr;
  }
}
</style>
